<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends TT_Controller {
	const DIVIDE = '`;`';
	public function index($page = 'customer/create_article')
	{
		$page = str_replace(self::DIVIDE, '/', urldecode($page));
		//Check to see if user is already logged in
		if($this->is_logged_in())
			redirect($page);
		// If not then show login form and ask user to enter username and password
		else {
			// Load files for creating form and validating form
			$this->load->helper('form');
			$this->load->library('session');
			if($this->input->post('login') != NULL ) {
				$this->load->library('ttvalidation');
				$validation = new Ttvalidation();
				
				$errors = array();
				
				$username = $validation->prepare_string($this->input->post('username'));
				$password = $validation->prepare_string($this->input->post('password'));
				
				if(empty($username)) {
					$errors['username'] = 'Vui lòng nhập tên đăng nhập';
					$this->template->build('login_form', array('errors' => $errors));
					return;
				}
				
				$this->load->model('login_model');
				$row = $this->login_model->get_customer($username, $password);
				if(count($row) > 1) {
					$user = array(
						'username' => $username,
						'userid' => $row['pi_id'],
						'cust_role' => 'customer',
						'logged_in' => TRUE
					);
					$this->session->set_userdata($user);
					
					redirect($page);					
				} else {
					$errors['wrong'] = 'Tên đăng nhập hoặc mật khẩu không đúng';
					$this->template->build('login_form', array('errors' => $errors));
				} 	
			}
			else $this->template->build('login_form');
		} 
		 
		
		
	}
	
	public function check_logged_in() {
		$url = urlencode(str_replace('/', self::DIVIDE , str_replace(base_url(), '', current_url())));
		/*echo $url;
		echo '<br/>' . urldecode($url);
		exit();*/
		if(!$this->is_logged_in()) {
			redirect('login/page/' . $url);
		} 
	}
	
	/*
	check to see if session has user loggin information
	*/
	private function is_logged_in() {
		$this->load->library('session');
		$logged_in = $this->session->userdata('logged_in');
		$role = $this->session->userdata('cust_role');
		return isset($logged_in) 
			&& $logged_in == TRUE 
			&& $role == 'customer';
	}
	
}

/* End of file login.php */
/* Location: ./application/modules/login/controllers/login.php */